//
//  MeViewController.swift
//  puretennis
//
//  Created by IYE Technologies on 12/25/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class MyDetailsViewController: ImagePickerController {
    
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var nicknameLabel: UILabel!
    @IBOutlet weak var accumulatedPointsLabel: UILabel!
    @IBOutlet weak var playYearButton: UIButton!
    @IBOutlet weak var qianDaoDaysLabel:UILabel!;
    @IBOutlet weak var qiandaoButton: UIButton!
    
    var playYear:NSDictionary!;
    var datePicker:PlaySinceDatePicker!;
    
    var newsLabel: UILabel!
    var newsListView: NewsListView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ViewUtils.addBackgroundView(self);
        self.navigationItem.titleView = ViewUtils.titleView("我");
        self.addLogoutBarItem();
        self.avatarImageView.layer.masksToBounds = true;
        self.avatarImageView.layer.cornerRadius = 8;
        self.qiandaoButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal);
        self.qiandaoButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Disabled);
        self.addChoiceAvatarButton();
        self.initnavigation();
    }
    
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        newsListView.removeFromSuperview()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        initNewsListView()
    }
    
    func initNewsListView(){
        newsLabel = ViewUtils.label("清新网球资讯", fontSize: 16)
        newsLabel.frame.origin.x = avatarImageView.frame.origin.x
        newsLabel.frame.origin.y = avatarImageView.frame.height + avatarImageView.frame.origin.y + 5
        self.view.addSubview(newsLabel)        
        newsListView = NewsListView()
        newsListView.frame.origin.x = newsLabel.frame.origin.x
        newsListView.frame.origin.y = newsLabel.frame.height + newsLabel.frame.origin.y + 5
        newsListView.frame.size.width = self.view.frame.width * 0.98
        newsListView.frame.size.height = self.view.frame.height - newsListView.frame.origin.y - self.tabBarHeight()!
        newsListView.loadNews(Method.NEWEST)
        newsListView.setupRefreshGesture()
        self.view.addSubview(newsListView)
        
    }
    
    func initnavigation(){
        var appointmentButtion = UIButton();
        appointmentButtion.setImage(UIImage(named: "arrow"), forState: UIControlState.Normal);
        appointmentButtion.showsTouchWhenHighlighted = true;
        appointmentButtion.sizeToFit();
        appointmentButtion.addTarget(self, action: Selector("showMenu:"), forControlEvents: UIControlEvents.TouchUpInside);
        var rightBarButtionItem = UIBarButtonItem(customView: appointmentButtion);
        self.navigationItem.rightBarButtonItem = rightBarButtionItem;
    }
    
    func showMenu(sender:UIButton){
        var frame = self.navigationController!.navigationBar.frame;
        frame.origin.x = self.navigationItem.rightBarButtonItem!.customView!.frame.origin.x;
        frame.size.width = self.navigationItem.rightBarButtonItem!.customView!.frame.width;
        
        var eidtMyInfo = KxMenuItem("修改资料",image: nil,target: self,action: Selector("editMyInfo:"));
        var logout = KxMenuItem("退出",image: nil,target: self,action: Selector("logout:"));
        KxMenu.setTitleFont(Utils.defaultFont());
        KxMenu.showMenuInView(self.navigationController!.view, fromRect: frame, menuItems: [eidtMyInfo,logout]);
    }
    
    func editMyInfo(sender:KxMenuItem){
        var storyboard = UIStoryboard(name: "Me", bundle: nil);
        var editMyInfoViewController = storyboard.instantiateViewControllerWithIdentifier("editMyInfoView") as EditMyInfoViewController;
        self.navigationController?.pushViewController(editMyInfoViewController, animated: true);
    }
    
    // Logout
    func logout(sender:KxMenuItem){
        let storyboard = UIStoryboard(name: "Login", bundle: nil);
        let loginView = storyboard.instantiateViewControllerWithIdentifier("loginView") as LoginViewController;
        self.presentViewController(loginView, animated: true) { () -> Void in
            AuthorisationService.logout();
        }
    }
    
    func addChoiceAvatarButton(){
        var choiceAvatarButton = UIButton();
        choiceAvatarButton.frame = self.avatarImageView.frame;
        choiceAvatarButton.addTarget(self, action: Selector("choiceAvatar:"), forControlEvents: UIControlEvents.TouchUpInside);
        self.view.addSubview(choiceAvatarButton);
    }
    
    func choiceAvatar(sender:UIButton){
        self.pickingImage();
    }
    
    override func didFinishPickingImage(image: UIImage!) {
        self.avatarImageView.image = image;
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        self.showTabBar();
        self.loadDetails();
        self.loadAvatar();
    }
    
    func loadAvatar(){
        var userGuid = Utils.currentUserGuid();
        var image = ImageUtils.retrieveUserImage(userGuid,reload: true);
        self.avatarImageView.image = image;
    }
    
    func loadDetails(){
        self.processing();
        var url = "/api/v1/user/myqiandao"
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            self.updateDetails(response);
            }, errorHandle: { (error) -> Void in
                self.processComplete();
        });
    }
    
    func updateDetails(response:AnyObject?){
        var userDetails = response as NSDictionary;
        
        var user = userDetails.objectForKey("user") as NSDictionary;
        var name = user.objectForKey("name") as String;
        self.nicknameLabel.text = name;
        var qianDao = userDetails.objectForKey("qianDao") as NSDictionary;
        var accumulatedPoints = qianDao.objectForKey("accumulatedPoints") as Int;
        self.accumulatedPointsLabel.text = "\(accumulatedPoints)";
        var canQianDao = qianDao.objectForKey("canQianDao") as Bool;
        var qianDaoDays = qianDao.objectForKey("qianDaoDays") as Int;
        self.updateQianDaoInfo(canQianDao,qianDaoDays: qianDaoDays);
        
        self.playYear = userDetails.objectForKey("playYear") as NSDictionary;
        var playYear = self.playYear.objectForKey("playYear") as String;
        self.playYearButton.setTitle(playYear, forState: UIControlState.Normal);
        
        self.processComplete();
    }
    
    func updateQianDaoInfo(enabled:Bool,qianDaoDays:Int){
        var title = enabled ? "签到" : "已签到";
        self.qiandaoButton.enabled = enabled;
        self.qiandaoButton.setTitle(title, forState: UIControlState.Normal);
        self.qiandaoButton.sizeToFit();
        self.qianDaoDaysLabel.text = "连续签到\(qianDaoDays)天";
        self.qianDaoDaysLabel.sizeToFit();
    }
    
    func addLogoutBarItem(){
        var barButtonItem = UIBarButtonItem(title: "Logout", style: UIBarButtonItemStyle.Plain, target: self, action: "logout");
        self.navigationItem.rightBarButtonItem = barButtonItem;
    }
    
    @IBAction func qiandao(sender: UIButton) {
        self.processing();
        var url = "/api/v1/user/qiandao";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var qianDao = response as NSDictionary;
            var accumulatedPoints = qianDao.objectForKey("accumulatedPoints") as Int;
            var qianDaoDays = qianDao.objectForKey("qianDaoDays") as Int
            self.accumulatedPointsLabel.text = "\(accumulatedPoints)";
            self.updateQianDaoInfo(false, qianDaoDays: qianDaoDays);
            self.processComplete();
        }, errorHandle: { (error) -> Void in
            self.processComplete();
        });
    }
    
    @IBAction func showDatePicker(sender: UIButton) {
        if(self.datePicker == nil){
            var originY = self.avatarImageView.frame.origin.y + self.avatarImageView.frame.height + 10;
            var width = self.view.frame.width;
            var height = self.view.frame.height - originY;
            var frame = CGRect(x: 0, y: originY, width: width, height: height);
            self.datePicker = PlaySinceDatePicker(frame: frame);
            self.datePicker.addConfirmCallback(updatedPlaySince);
            
            var year = self.playYear.objectForKey("year") as Int;
            var month = self.playYear.objectForKey("month") as Int;
            Utils.debug("Year [\(year)\n[\(month)]]");
            self.datePicker.selectDate(year, month: month);
            self.tabBarController!.view.addSubview(self.datePicker);
        }
        self.datePicker.show();
    }
    
    func updatedPlaySince(response:AnyObject?){
        var playYearDictionary = response as NSDictionary;
        var playYear = playYearDictionary.objectForKey("playYear") as String;
        self.playYearButton.setTitle(playYear, forState: UIControlState.Normal);
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        Utils.debug("Memory warning")
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated);
        KxMenu.dismissMenu();
    }
}
